<?php
use addons\cloudstorage\model\CloudStorage;
use addons\cloudstorage\driver\Aliyun;
use addons\cloudstorage\driver\Qiniu;
use addons\cloudstorage\driver\Tencent;
use think\Exception;
use think\facade\Config;

// 上传钩子
add_hook('upload_after', function ($params) {
    // 获取当前配置的默认存储
    $storage = CloudStorage::getDefault();
    if (!$storage) {
        return; // 使用默认本地存储
    }
    
    // 移除本地文件
    @unlink($params['file']->getRealPath());
    
    try {
        // 根据存储类型实例化对应驱动
        $driver = null;
        switch ($storage['type']) {
            case 'aliyun':
                $driver = new Aliyun($storage['config'], $storage['domain']);
                break;
            case 'qiniu':
                $driver = new Qiniu($storage['config'], $storage['domain']);
                break;
            case 'tencent':
                $driver = new Tencent($storage['config'], $storage['domain']);
                break;
            default:
                return;
        }
        
        // 上传到云存储
        $result = $driver->upload($params['file'], $params['savepath']);
        
        if (!$result['status']) {
            throw new Exception($result['msg']);
        }
        
        // 更新上传结果
        $params['info']['savepath'] = dirname($result['path']) . '/';
        $params['info']['savename'] = basename($result['path']);
        $params['info']['url'] = $result['url'];
        
    } catch (Exception $e) {
        // 上传失败处理
        throw new Exception('云存储上传失败: ' . $e->getMessage());
    }
});

// 删除文件钩子
add_hook('upload_delete', function ($params) {
    // 获取当前配置的默认存储
    $storage = CloudStorage::getDefault();
    if (!$storage) {
        return; // 使用默认本地存储
    }
    
    try {
        // 根据存储类型实例化对应驱动
        $driver = null;
        switch ($storage['type']) {
            case 'aliyun':
                $driver = new Aliyun($storage['config'], $storage['domain']);
                break;
            case 'qiniu':
                $driver = new Qiniu($storage['config'], $storage['domain']);
                break;
            case 'tencent':
                $driver = new Tencent($storage['config'], $storage['domain']);
                break;
            default:
                return;
        }
        
        // 从云存储删除文件
        $filePath = ltrim(str_replace($storage['domain'], '', $params['url']), '/');
        $driver->delete($filePath);
        
    } catch (Exception $e) {
        // 记录错误但不中断执行
        trace('云存储删除失败: ' . $e->getMessage(), 'error');
    }
});
?>
